from flask import Blueprint, request, jsonify, send_file
from models import db, DictionaryType, DictionaryItem
from io import BytesIO
from openpyxl import Workbook
from openpyxl.styles import Font, Alignment, PatternFill, Border, Side
from routes.certificate import adjust_column_width

bp = Blueprint('dict', __name__, url_prefix='/api/dict')

# 字典类型 CRUD
@bp.route('/types', methods=['GET'])
def get_types():
    types = DictionaryType.query.order_by(DictionaryType.id.desc()).all()
    return jsonify([t.to_dict() for t in types])

@bp.route('/types', methods=['POST'])
def create_type():
    data = request.json
    t = DictionaryType(
        code=data['code'],
        name=data['name'],
        description=data.get('description', ''),
        status=data.get('status', 1)
    )
    db.session.add(t)
    db.session.commit()
    return jsonify(t.to_dict()), 201

@bp.route('/types/<int:type_id>', methods=['PUT'])
def update_type(type_id):
    t = DictionaryType.query.get_or_404(type_id)
    data = request.json
    t.code = data.get('code', t.code)
    t.name = data.get('name', t.name)
    t.description = data.get('description', t.description)
    t.status = data.get('status', t.status)
    db.session.commit()
    return jsonify(t.to_dict())

@bp.route('/types/<int:type_id>', methods=['DELETE'])
def delete_type(type_id):
    t = DictionaryType.query.get_or_404(type_id)
    db.session.delete(t)
    db.session.commit()
    return '', 204

@bp.route('/types/export/excel', methods=['GET'])
def export_dict_types_excel():
    wb = Workbook()
    ws = wb.active
    ws.title = '字典类型'
    headers = ['编码', '名称', '描述', '状态']
    # 表头样式
    header_font = Font(bold=True, size=12, color='FFFFFF', name='微软雅黑')
    header_fill = PatternFill(fill_type='solid', fgColor='91C36A')
    center_alignment = Alignment(horizontal='center', vertical='center')
    thin_gray_border = Border(
        left=Side(style='thin', color='CCCCCC'),
        right=Side(style='thin', color='CCCCCC'),
        top=Side(style='thin', color='CCCCCC'),
        bottom=Side(style='thin', color='CCCCCC')
    )
    ws.append(headers)
    for col, _ in enumerate(headers, 1):
        cell = ws.cell(row=1, column=col)
        cell.font = header_font
        cell.fill = header_fill
        cell.alignment = center_alignment
        cell.border = thin_gray_border
        ws.row_dimensions[1].height = 24
    # 数据
    types = DictionaryType.query.order_by(DictionaryType.id.desc()).all()
    content_font = Font(name='宋体', size=11, color='000000')
    left_alignment = Alignment(horizontal='left', vertical='center')
    for idx, t in enumerate(types, start=2):
        row = [
            t.code,
            t.name,
            t.description,
            '启用' if t.status == 1 else '禁用',
        ]
        ws.append(row)
        for col_idx, _ in enumerate(row, start=1):
            cell = ws.cell(row=idx, column=col_idx)
            cell.font = content_font
            cell.alignment = left_alignment
            cell.border = thin_gray_border
            cell.fill = PatternFill('solid', fgColor='FFFFFF')
            ws.row_dimensions[idx].height = 14
    # 自动列宽
    adjust_column_width(ws, types)
    output = BytesIO()
    wb.save(output)
    output.seek(0)
    return send_file(
        output,
        as_attachment=True,
        download_name='字典类型.xlsx',
        mimetype='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
    )

# 字典项 CRUD
@bp.route('/items', methods=['GET'])
def get_items():
    type_code = request.args.get('type_code', type=str)
    q = DictionaryItem.query
    if type_code:
        q = q.filter_by(type_code=type_code)
    items = q.order_by(DictionaryItem.sort_order, DictionaryItem.id).all()
    return jsonify([i.to_dict() for i in items])

@bp.route('/items', methods=['POST'])
def create_item():
    data = request.json
    item = DictionaryItem(
        type_code=data['type_code'],
        value=data['value'],
        label=data['label'],
        sort_order=data.get('sort_order', 0),
        status=data.get('status', 1),
        remark=data.get('remark', '')
    )
    db.session.add(item)
    db.session.commit()
    return jsonify(item.to_dict()), 201

@bp.route('/items/<int:item_id>', methods=['PUT'])
def update_item(item_id):
    item = DictionaryItem.query.get_or_404(item_id)
    data = request.json
    item.value = data.get('value', item.value)
    item.label = data.get('label', item.label)
    item.sort_order = data.get('sort_order', item.sort_order)
    item.status = data.get('status', item.status)
    item.remark = data.get('remark', item.remark)
    db.session.commit()
    return jsonify(item.to_dict())

@bp.route('/items/<int:item_id>', methods=['DELETE'])
def delete_item(item_id):
    item = DictionaryItem.query.get_or_404(item_id)
    db.session.delete(item)
    db.session.commit()
    return '', 204

# 通过类型编码获取字典项（前端下拉专用）
@bp.route('/items/by_code/<code>', methods=['GET'])
def get_items_by_code(code):
    items = DictionaryItem.query.filter_by(type_code=code, status=1).order_by(DictionaryItem.sort_order, DictionaryItem.id).all()
    return jsonify([i.to_dict() for i in items])

@bp.route('/items/export/excel', methods=['GET'])
def export_dict_items_excel():
    type_code = request.args.get('type_code', type=str)
    q = DictionaryItem.query
    if type_code:
        q = q.filter_by(type_code=type_code)
    items = q.order_by(DictionaryItem.sort_order, DictionaryItem.id).all()
    wb = Workbook()
    ws = wb.active
    ws.title = '字典项'
    headers = ['类型编码', '显示文本', '选项值', '排序', '状态', '备注']
    # 表头样式
    header_font = Font(bold=True, size=12, color='FFFFFF', name='微软雅黑')
    header_fill = PatternFill(fill_type='solid', fgColor='91C36A')
    center_alignment = Alignment(horizontal='center', vertical='center')
    thin_gray_border = Border(
        left=Side(style='thin', color='CCCCCC'),
        right=Side(style='thin', color='CCCCCC'),
        top=Side(style='thin', color='CCCCCC'),
        bottom=Side(style='thin', color='CCCCCC')
    )
    ws.append(headers)
    for col, _ in enumerate(headers, 1):
        cell = ws.cell(row=1, column=col)
        cell.font = header_font
        cell.fill = header_fill
        cell.alignment = center_alignment
        cell.border = thin_gray_border
        ws.row_dimensions[1].height = 24
    # 内容样式
    content_font = Font(name='宋体', size=11, color='000000')
    left_alignment = Alignment(horizontal='left', vertical='center')
    for idx, item in enumerate(items, start=2):
        row = [
            item.type_code,
            item.label,
            item.value,
            item.sort_order,
            '启用' if item.status == 1 else '禁用',
            item.remark,
        ]
        ws.append(row)
        for col_idx, _ in enumerate(row, start=1):
            cell = ws.cell(row=idx, column=col_idx)
            cell.font = content_font
            cell.alignment = left_alignment
            cell.border = thin_gray_border
            cell.fill = PatternFill('solid', fgColor='FFFFFF')
            ws.row_dimensions[idx].height = 14
    # 自动列宽
    adjust_column_width(ws, items)
    output = BytesIO()
    wb.save(output)
    output.seek(0)
    return send_file(
        output,
        as_attachment=True,
        download_name='字典项.xlsx',
        mimetype='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
    ) 